import { useEffect } from "react"

export default function useLazyLoading() {
    useEffect(() => {
        setTimeout(() => {
            checkImages()
        }, 1)
        window.addEventListener('scroll', checkImages)
        return () => {
            window.removeEventListener("scroll", checkImages)
        }
    }, [])
    const checkImages = () => {
        var imgs = document.querySelectorAll('img')
        imgs.forEach((item, index) => {
            if (isInClient(item) && item.src === '') {
                item.src = item.getAttribute('datasrc')
            }
        })
    }
    const isInClient = (item) => {
        var offset = item.getBoundingClientRect()
        var bodyHeight = document.body.offsetHeight
        if ((offset.top > 0 && offset.top < bodyHeight + (bodyHeight / 2)) || (offset.bottom > 0 && offset.bottom < bodyHeight + (bodyHeight / 2))) {
            return true
        }
        else {
            return false
        }
    }
}
